package org.shean.app.rssreader;

import java.util.ArrayList;

import org.shean.app.rssreader.provider.SzRSSReader;

import android.app.Activity;
import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AlphabetIndexer;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class TagListActivity extends ListActivity {
	private TagListAdapter mAdapter;
	private Cursor mTagCursor;
	private boolean mAdapterSent = false;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.channel_picker_activity);
		ListView lv = getListView();
		lv.setFastScrollEnabled(true);
		lv.setOnCreateContextMenuListener(this);
		lv.setTextFilterEnabled(true);

		mAdapter = (TagListAdapter) getLastNonConfigurationInstance();
		if (mAdapter == null) {
			// Log.i("@@@", "starting query");
			mAdapter = new TagListAdapter(getApplication(), this,
					R.layout.channel_list_item, mTagCursor,
					new String[] {}, new int[] {});
			setListAdapter(mAdapter);
			setTitle(R.string.app_name);
			getTagCursor(mAdapter.getQueryHandler(), null);
		} else {
			mAdapter.setActivity(this);
			setListAdapter(mAdapter);
			mTagCursor = mAdapter.getCursor();
			if (mTagCursor != null) {
				init(mTagCursor);
			} else {
				getTagCursor(mAdapter.getQueryHandler(), null);
			}
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (mTagCursor != null) {
			mTagCursor.requery();
		}
		getListView().invalidateViews();
	}

	@Override
	public void onPause() {
		mReScanHandler.removeCallbacksAndMessages(null);
		super.onPause();
	}

	@Override
	public void onDestroy() {
		if (!mAdapterSent) {
			Cursor c = mAdapter.getCursor();
			if (c != null) {
				c.close();
			}
		}
		super.onDestroy();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Uri uri = ContentUris.withAppendedId(
				SzRSSReader.Tags.CONTENT_URI, id);
		startActivity(new Intent(Intent.ACTION_VIEW, uri));
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		mAdapterSent = true;
		return mAdapter;
	}
	
	public static final int ADD_ID = Menu.FIRST;
	public static final int DELETE_ALL_ID = Menu.FIRST + 1;
	public static final int DELETE_ZERO_ID = Menu.FIRST + 2;
	
	public static final int Remove_ALL_ID = Menu.FIRST +3;
	public static final int RENAME_ID = Menu.FIRST + 4;
	public static final int DELETE_ID = Menu.FIRST + 5;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, ADD_ID, 0, "Add New Tag");
		menu.add(0, DELETE_ALL_ID, 1, "Delete All");
		//menu.add(0, DELETE_ZERO_ID, 2, "Delete All Zero");
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case DELETE_ALL_ID:
			this.getContentResolver().delete(SzRSSReader.Tags.CONTENT_URI,null,null);
			mTagCursor.requery();
			getListView().invalidateViews();
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo info) {
		menu.setHeaderTitle("Tag Menu");
		// menu.setHeaderIcon(R.drawable.feedicon);
		menu.add(1, Remove_ALL_ID, 0, "Remove All");
		menu.add(1, RENAME_ID, 1, "Rename");
		menu.add(1, DELETE_ID, 2, "Delete");
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {

		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case DELETE_ID:
			Uri uri = ContentUris.withAppendedId(
					SzRSSReader.Tags.CONTENT_URI, menuInfo.id);
			this.getContentResolver().delete(uri,null,null);
			mTagCursor.requery();
			getListView().invalidateViews();
			return true;
		}
		return super.onContextItemSelected(item);
	}
	
	public void init(Cursor c) {
		mAdapter.changeCursor(c); // also sets mArtistCursor

		if (mTagCursor == null) {
			closeContextMenu();
			mReScanHandler.sendEmptyMessageDelayed(0, 1000);
			return;
		}
	}
	
	private Handler mReScanHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			getTagCursor(mAdapter.getQueryHandler(), null);
		}
	};
	
	private String[] mCols = new String[] { SzRSSReader.Tags._ID,
			SzRSSReader.Tags.NAME };
	
	private Cursor getTagCursor(AsyncQueryHandler async, String filter) {

		Cursor ret = null;

		if (async != null) {
			async.startQuery(0, null, SzRSSReader.Tags.CONTENT_URI, mCols,
					null, null, null);
		} else {
			ret = managedQuery(SzRSSReader.Tags.CONTENT_URI, mCols, null,
					null, null);
		}

		return ret;
	}

	
	static class TagListAdapter extends SimpleCursorAdapter {

		private AsyncQueryHandler mQueryHandler;
		private TagListActivity mActivity;
		private final BitmapDrawable mDefaultIcon;
		// private final Resources mResources;

		private int mTitleIdx;
		private int mIdIdx;
		// private AlphabetIndexer mIndexer;

		private boolean mConstraintIsValid = false;
		private String mConstraint = null;

		class ViewHolder {
			TextView line1;
			TextView line2;
			TextView number;
			// ImageView play_indicator;
			ImageView icon;
			// ProgressBar download_progress;
			ViewFlipper flipper;
		}

		class QueryHandler extends AsyncQueryHandler {
			QueryHandler(ContentResolver res) {
				super(res);
			}

			@Override
			protected void onQueryComplete(int token, Object cookie,
					Cursor cursor) {
				// Log.i("@@@", "query complete");
				mActivity.init(cursor);
			}
		}

		public TagListAdapter(Context context,
				TagListActivity currentactivity, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
			mActivity = currentactivity;
			mQueryHandler = new QueryHandler(context.getContentResolver());

			Resources r = context.getResources();

			Bitmap b = BitmapFactory.decodeResource(r, R.drawable.rss_channel);
			mDefaultIcon = new BitmapDrawable(b);
			// no filter or dither, it's a lot faster and we can't tell the
			// difference
			mDefaultIcon.setFilterBitmap(false);
			mDefaultIcon.setDither(false);
			getColumnIndices(c);
			// mResources = context.getResources();
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			View v = super.newView(context, cursor, parent);
			ViewHolder vh = new ViewHolder();
			vh.line1 = (TextView) v.findViewById(R.id.line1);
			vh.line2 = (TextView) v.findViewById(R.id.line2);
			vh.number = (TextView) v.findViewById(R.id.number);
			// vh.play_indicator = (ImageView)
			// v.findViewById(R.id.play_indicator);
			vh.icon = (ImageView) v.findViewById(R.id.icon);
			vh.flipper = (ViewFlipper) v.findViewById(R.id.flipper);
			// vh.icon.setBackgroundDrawable(mDefaultIcon);
			vh.icon.setPadding(0, 0, 1, 0);
			
			vh.flipper.setInAnimation(AnimationUtils.loadAnimation(mActivity,
                    R.anim.push_left_in));
			vh.flipper.setOutAnimation(AnimationUtils.loadAnimation(mActivity,
                    R.anim.push_left_out));
			// vh.download_progress = (ProgressBar)
			// v.findViewById(R.id.download_progress);
			v.setTag(vh);
			return v;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {

			ViewHolder vh = (ViewHolder) view.getTag();

			String name = cursor.getString(mTitleIdx);
			vh.line2.setText(name);
			ImageView iv = vh.icon;
			iv.setImageDrawable(mDefaultIcon);

			long tagId = cursor.getLong(mIdIdx);

			Uri uri = SzRSSReader.PostTags.CONTENT_URI;

			Cursor unread = context.getContentResolver().query(uri,
					new String[] { SzRSSReader.Posts._ID }, SzRSSReader.PostTags.TAG_ID + "='" + tagId + "'" , null,
					null);

			int tagCount = unread.getCount();
			unread.close();

			vh.number.setText("" + tagCount);
			
			vh.line2.setVisibility(View.VISIBLE);
			vh.flipper.setVisibility(View.GONE);
			
		}

		@Override
		public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
			String s = constraint.toString();
			if (mConstraintIsValid
					&& ((s == null && mConstraint == null) || (s != null && s
							.equals(mConstraint)))) {
				return getCursor();
			}
			Cursor c = mActivity.getTagCursor(null, s);
			mConstraint = s;
			mConstraintIsValid = true;
			return c;
		}

		/*
		 * public int getPositionForSection(int section) { return
		 * mIndexer.getPositionForSection(section); }
		 * 
		 * public int getSectionForPosition(int position) { return 0; }
		 * 
		 * public Object[] getSections() { return mIndexer.getSections(); }
		 */
		public AsyncQueryHandler getQueryHandler() {
			return mQueryHandler;
		}

		public void setActivity(TagListActivity newactivity) {
			mActivity = newactivity;
		}

		@Override
		public void changeCursor(Cursor cursor) {
			if (cursor != mActivity.mTagCursor) {
				mActivity.mTagCursor = cursor;
				getColumnIndices(cursor);
				super.changeCursor(cursor);
			}
		}

		private void getColumnIndices(Cursor cursor) {

			if (cursor != null) {
				mTitleIdx = cursor.getColumnIndexOrThrow(SzRSSReader.Tags.NAME);
				mIdIdx = cursor.getColumnIndexOrThrow(SzRSSReader.Tags._ID);
			}
		}

		class ChannelAlphabetIndexer extends AlphabetIndexer {

			public ChannelAlphabetIndexer(Cursor cursor, int sortedColumnIndex,
					CharSequence alphabet) {
				super(cursor, sortedColumnIndex, alphabet);
			}

			@Override
			protected int compare(String word, String letter) {
				// String wordKey = MediaStore.Audio.keyFor(word);
				// String letterKey = MediaStore.Audio.keyFor(letter);
				String wordKey = word;
				String letterKey = letter;

				if (wordKey.startsWith(letter)) {
					return 0;
				} else {
					return wordKey.compareTo(letterKey);
				}
			}
		}

	}

}
